package name.suray.andrey;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class ParseUnit {
	
	private IParser p;
	
	
	
	public IParser getIParser(){
		return p;
	}
	
	
	
	public Map<String,String> parse() throws FileNotFoundException, IOException{
		
		System.out.println("In ParseUnit.parse()...");
		File f = new File("D:\\config.xml");
		
		if(f.exists()){
			p = new XML();
			Map<String,String> map = p.parse();
			makeFile(map);
			return map;				
		}else{
			System.out.println("No xml file...");
			f = new File("D:\\config.properties");
			
			if(f.exists()){
				p = new Prop();
				Map<String,String> map = p.parse();
				makeFile(map);
				return map;								
			}else 
				System.out.println("Config file not found!");
				System.out.println("Put config.xml or config.properties to D:\\");
				throw new FileNotFoundException("Config file not found! Expected config.xml or config.properties");		
		}
		
	}// end of parse
	
	
	
	private void makeFile(Map<String, String> map){
		
		Velocity.init();
        VelocityContext vc = new VelocityContext();
        vc.put("class", map.get("class"));
        vc.put("field1", map.get("field1"));
        vc.put("field2", map.get("field2"));
        vc.put("field3", map.get("field3"));
        Template template = Velocity.getTemplate("velocity.vm", "utf-8");
        
        try {
        	
	        BufferedWriter bw = 
	        	new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src\\name\\suray\\andrey\\" + map.get("class") + ".java")));
	        template.merge(vc, bw);
			bw.flush();
			bw.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}//end of makeFile
	
	
	
}// end of class ParseUnit
